﻿using PEProtocol;

/**
 * 购买资源系统
 */

public class BuySys{
    private static BuySys instance = null;

    public static BuySys Instance{
        get{
            if (instance == null){
                instance = new BuySys();
            }

            return instance;
        }
    }

    private CacheSvc cacheSvc;

    public void Init(){
        cacheSvc = CacheSvc.Instance;
        PECommon.Log("BuySys Init Done");
    }

    public void ReqBuy(MsgPack pkt){
        ReqBuy data = pkt.msg.reqBuy;
        GameMsg msg = new GameMsg{
            cmd = (int)CMD.ResBuy,
        };

        PlayerData pd = cacheSvc.GetPlayerDataBySession(pkt.session);
        if (pd.diamond < data.cost){
            msg.err = (int)ErrorCode.LackDiamond;
        }
        else{
            pd.diamond -= data.cost;
            PshTaskPrg pshTaskPrg = null;
            switch (data.type){
                case 0:
                    pd.power += 100;
                    pshTaskPrg = TaskSys.Instance.GetTaskPrgs(pd, 4);
                    break;
                case 1:
                    pd.coin += 1000;
                    pshTaskPrg = TaskSys.Instance.GetTaskPrgs(pd, 5);
                    break;
            }

            if (!cacheSvc.UpdatePlayerData(pd.id, pd)){
                msg.err = (int) ErrorCode.UpdateDBError;
            }
            else{
                msg.resBuy = new ResBuy{
                    type = data.type,
                    dimond = pd.diamond,
                    coin = pd.coin,
                    power = pd.power
                };
                
                //并包处理
                msg.pshTaskPrg = pshTaskPrg;
            }
        }
        pkt.session.SendMsg(msg);
    }
}
